import { addDept, getDeptInfo, queryDeptList, updateDept } from '@/services/system/SystemController';
import {
  ModalForm,
  ProFormDigit,
  ProFormSwitch,
  ProFormText,
  ProFormTextArea,
  ProFormTreeSelect,
} from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import { Form, message } from 'antd';

export interface DeptInfo {
  dept_id: number;
  dept_name: string;
  order_num: number;
  parent_id: number;
  status: boolean;
  created_at: string;
  description: string;
}

const DeptForm: React.FC<{
  id: number | null;
  p_id: number | null;
  onClose: () => void;
  onFinish: () => void;
}> = ({ id, p_id, onClose, onFinish }) => {
  const [form] = Form.useForm<System.DeptInfo>();

  useRequest(() => id !== null && id != 0 ? getDeptInfo(id) : Promise.resolve(), {
    throwOnError: true,
    refreshDeps: [id],
    onSuccess(d) {
      if (!d && p_id) {
        form.setFieldValue("parent_id", p_id)
      } else {
        form.setFieldsValue(d)
      }
    },
  })

  let { loading: submiting, run: submit } = useRequest((data) => id === null ? Promise.reject("null id") : id != 0 ? updateDept(id, data) : addDept(data), {
    manual: true,
    throwOnError: true,
    onError(e, params) {
      message.error("操作失败")
    },
    onSuccess() {
      onFinish();
    },
  })

  return (
    <ModalForm<DeptInfo>
      title={id ? `编辑单位：${form.getFieldValue("dept_name")}` : '新建单位'}
      open={id !== null}
      form={form}
      width={450}
      layout="horizontal"
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
        onCancel: onClose,
      }}
      submitTimeout={2000}
      loading={submiting}
      onFinish={submit}
    >
      <div className='py-2'></div>
      <ProFormTreeSelect
        name="parent_id"
        label="上级部门"
        placeholder="请选择上级部门"
        required
        fieldProps={{
          fieldNames: {
            label: 'dept_name',
            value: 'dept_id',
          },
        }}
        request={async () => {
          let { data } = await queryDeptList({ status: true })
          return data;
        }}
      />
      <ProFormText
        name="dept_name"
        label="部门名称"
        placeholder="请输入部门名称"
        rules={[{ required: true, message: '请输入至少三个字符！', min: 3, max: 32, },]}
      />
      <ProFormDigit name="order_num" label="显示排序" placeholder="请输入显示排序" required />
      <ProFormTextArea name="description" label="单位描述" placeholder="请输入单位描述" />
      <ProFormSwitch name={'status'} label="状态" />
    </ModalForm>
  );
};

export default DeptForm;
